#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/inotify.h>

#define BUFLEN (4 * 1024)

int
main(int argc, char *argv[])
{
	int fd;
	int wd;

	char buf[BUFLEN];

	fd = inotify_init();

	if (fd < 0) {
		perror("inotify_init1: ");
		exit(EXIT_FAILURE);
	}

	wd = inotify_add_watch(fd, ".", IN_ALL_EVENTS);

	ssize_t length = 0;
	int watch_lost = 0;

	for (; length = read(fd, buf, BUFLEN), length, !watch_lost;) {
		struct inotify_event *event = (struct inotify_event *)buf;

		while ((char *)event < buf + length) {
			printf("mask = %08X\n", event->mask);

			if (event->mask & IN_ISDIR) {
				if (event->len) {
					printf("\"%s\" is a directory.\n", event->name);
				} else {
					printf("The watch target is directory.\n");
				}
			}

			if (event->mask & IN_ACCESS) {
				if (event->len) {
					printf("\"%s\" has been accessed.\n", event->name);
				} else {
					printf("The watch target has been accessed.\n");
				}
			}

			if (event->mask & IN_MODIFY) {
				if (event->len) {
					printf("\"%s\" has been modified.\n", event->name);
				} else {
					printf("The watch target has been modified.\n");
				}
			}

			if (event->mask & IN_ATTRIB) {
				if (event->len) {
					printf("Atrribute of \"%s\" has been changed.\n", event->name);
				} else {
					printf("Atrribute of the watch target has been changed.\n");
				}
			}

			printf("\n");
			event = (struct inotify_event *)event->name + event->len;
		}
	}
	close(fd);
	printf("Quit.\n");
	exit(EXIT_SUCCESS);
}
